'use strict';

const fs = require('fs');

//1、找到所有的路由文件
function findControllers(path) {
    path = path || './controller/';//如果有指定路径则查找指定路径，如果没有指定路径则默认controller(运行时被引入到app中执行，所以其地址应该指定为./controller)
    // console.log(path);
    let files = fs.readdirSync(path);
    return files.filter(item => {
        return item !== 'index.js';
    });
}

//2、遍历注册所有的路由
function registryRouter(controllerFiles, router) {
    controllerFiles.forEach(item => {
        let tmpModule = require('../controller/' + item.replace('.js', ''));
        for (let key in tmpModule) {
            let tmpArr = key.split(' ');

            let method = tmpArr[0];
            let url = tmpArr[1];
            let fn = tmpModule[key];

            if (method === 'get') {
                router.get(url, fn);
            } else if (method === 'post') {
                router.post(url, fn);
            } else if (method === 'put') {
                router.put(url, fn);
            } else if (method === 'delete') {
                router.delete(url, fn);
            }
        }
    })

}

module.exports = {
    findControllers,
    registryRouter
}